/* eslint-disable default-case */
/* eslint-disable array-callback-return */
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import _ from 'lodash';
import {
  getEmpList,
  getCustomersList,
  getPlaSuppsList,
  getListByUserList,
  getsuppContList,
  getByCustIdList,
  getInfoList,
  getSuppIdList,
  getProductList,
  getCheckNameList,
  getUpdateDetail,
  getAccessList,
  getMatchList,
  getUpdateSubmit,
  getNextPeopleInfo,
  getUploadProgress,
  getSubProgress,
  finishData,
  isHavaEmpNumber,
  uploadFileQuoUpdate,
} from '@/services/quotation';
import * as service from '@/services/socket';

export default {
  state: {
    formFieldsValue: {},
    expandForm: false,
    pageData: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    batchQuery: {
      // 批量上传数据
      sendType: '1',
      tempFlag: '1',
      isSerSetFlag: '1',
      progressPercent: 0,
    },
    customerNameList: [],
    suppReplaceCorpId: '',
    supplyList: [],
    custId: '',
    contList: [],
    supplyContList: [],
    productData: [],
    updateDetailData: { quoState: 1 }, // 修改之前的查看
    originalData: {}, // 查看详情（无修改）
    taxes: '1', // 是否含税
    method: '2', // 报价方式
    subUpdateDetailData: {}, // 提交时用的数据
    suppList: [
      {
        // 打包产品列表
        id: new Date().getTime(),
        listQuoPd: '',
      },
    ],
    isGoBack: false,
    nextSubmitData: {}, // 点击下一步
    nextData: {}, // 第二步的数据
    nextFinishData: {}, // 上传文件的时候用
    getBatchId: null, // 批次号
    batchId: null, // 已启用 - 下载查看失败原因 - 批次号
    changQuoUpdateMessage: {},
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/batchAdj/export/error', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
      quoId: null,
      quoState: null,
    },
    isSubmitResult: false,
  },
  effects: {
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getEmpList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },

    // 获取客户名称
    *getCustomersData({ payload }, { call, put }) {
      const response = yield call(getCustomersList, payload);
      if (response.success) {
        yield put({
          type: 'getCustList',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
        yield put({
          type: 'getCustList',
          payload: {
            data: [],
          },
        });
      }
    },

    // 获取当前签约方
    *getPlaSuppData({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getPlaSuppsList, payload);
      if (response.success) {
        yield put({
          type: 'getSuppList',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
        yield put({
          type: 'getSuppList',
          payload: {
            data: [],
          },
        });
      }
      callback(response);
    },

    // 获取全部签约方
    *getListByUserData({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getListByUserList, payload);
      if (response.success) {
        yield put({
          type: 'getByUserList',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
        yield put({
          type: 'getByUserList',
          payload: {
            data: [],
          },
        });
      }
      callback(response);
    },

    // 通过供应商找客户名称
    *getsuppContData({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getsuppContList, payload);
      if (response.success) {
        yield put({
          type: 'getSuppsList',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
        yield put({
          type: 'getSuppsList',
          payload: {
            data: [],
          },
        });
      }
      callback(response);
    },

    // 通过客户名称找供应商
    *getByCustIdData({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getByCustIdList, payload);
      if (response.success && response.data) {
        yield put({
          type: 'getCustIdList',
          payload: {
            data: response.data,
          },
        });
      } else {
        yield put({
          type: 'getCustIdList',
          payload: {
            data: [],
          },
        });
      }
      callback(response);
    },

    // 商务合同入口：本地
    *getInfoData({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getInfoList, payload);
      if (response.success) {
        yield put({
          type: 'getInfosList',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
        yield put({
          type: 'getInfosList',
          payload: {
            data: [],
          },
        });
      }
      callback(response);
    },

    // 根据签约方为全国：请求供应商合同
    *getsuppIdData({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getSuppIdList, payload);
      if (response.success) {
        yield put({
          type: 'getSuppIdsData',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
        yield put({
          type: 'getSuppIdsData',
          payload: {
            data: [],
          },
        });
      }
      callback(response);
    },

    // 获取产品列表
    *getProductData({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getProductList, payload);
      if (response.success) {
        yield put({
          type: 'getProduct',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
        yield put({
          type: 'getProduct',
          payload: {
            data: [],
          },
        });
      }
      callback(response);
    },

    *getCheckNameData({ payload, callback = () => {} }, { call }) {
      const response = yield call(getCheckNameList, payload);
      callback(response);
    },

    // 修改前查看
    *updateDetail({ payload, callback = () => {} }, { call, put, select }) {
      const response = yield call(getUpdateDetail, payload);
      const productData = yield select(state => state.quoupdate.productData);
      response.data.allProductId = [];
      response.data.allProductList = [];
      const allProductList = [...productData];
      response.data.packList.map(item => {
        allProductList.push(...item.listQuoPd);
        item.listQuoPd.map(items => {
          if (productData.some(pdItem => pdItem.pdId === items.pdId)) {
            response.data.allProductId.push(items.pdId);
          } else {
            response.data.allProductId.push(items.pdName);
          }
        });
        response.data.allProductList = _.unionBy(allProductList, 'pdId');
      });

      yield put({
        type: 'getUpdateDetailData',
        payload: {
          data: [],
        },
      });
      if (response.success) {
        yield put({
          type: 'getUpdateDetailData',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(response.message || '服务端错误！');
        yield put({
          type: 'getUpdateDetailData',
          payload: {
            data: [],
          },
        });
      }
      callback(response.data);
    },

    // 获取产品属性
    *getAccess({ payload, callback = () => {} }, { call }) {
      const response = yield call(getAccessList, payload);
      callback(response);
    },

    *getMatch({ payload, callback = () => {} }, { call }) {
      const response = yield call(getMatchList, payload);
      callback(response);
    },

    // 修改提交
    updateSubmit:[
      function* ({ payload, callback = () => {} }, { call }) {
        const response = yield call(getUpdateSubmit, payload);
        callback(response);
      },
      {type:'throttle', ms:10000}
    ],

    // 已启用的进入人员信息页面前（ 调一个接口 ）
    *nextPeopleInfo({ payload }, { call, put }) {
      const response = yield call(getNextPeopleInfo, payload);
      if (response.success) {
        yield put({
          type: 'updateQuoData',
          payload: { data: response.data },
        });
        yield put({
          type: 'updateModelData',
          payload: { batchId: response.data && response.data.batchNo },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
      return response;
    },

    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },

    // 提交的时候的进度条
    *getProgress({ payload }, { call }) {
      const response = yield call(getSubProgress, payload);
      return response;
    },

    *getFinishData({ payload }, { call }) {
      const response = yield call(finishData, payload);
      return response;
    },

    // 是否有人员信息
    *isHavaEmp({ payload }, { call }) {
      const response = yield call(isHavaEmpNumber, payload);
      return response;
    },

    // 上传文件:批量进度
    *uploadFileWithProgress({ payload }, { call, put }) {
      const response = yield call(uploadFileQuoUpdate, payload);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            batchId: response.data && response.data.batchId,
            progressPercent: 0,
          },
        });
        if (response.data && response.data.successProp !== 100) {
          yield put({
            type: 'updateModelData',
            payload: {
              showProgress: true,
            },
          });
          yield call(service.socketChannel, {
            type: 'sub',
            data: { to: response.data && (response.data.batchId || response.data), type: 'task' },
          });
        } else {
          yield put({
            type: 'updateBatchTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '上传失败'}`);
      }
      return response;
    },

    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select, call }) {
      const { batchId, isSubmitResult, routerParam } = yield select(state => state.quoupdate);
      if (Number(batchId) === Number(payload.batchId)) {
        if (isSubmitResult) {
          if (payload.next) {
            yield put({
              type: 'updateModelData',
              payload: {
                batchId: payload.next && payload.next.batchId,
                progressPercent: 0,
                showProgress: true,
                isSubmitResult: true,
              },
            });
            yield call(service.socketChannel, {
              type: 'sub',
              data: { to: payload.next && payload.next.batchId, type: 'task' },
            });
          } else {
            yield put({
              type: 'updateSubmitBatchTask',
              payload,
            });
            if (payload.successProp === 100) {
              yield put(
                routerRedux.push(
                  `/salemanage/quotation/updatefinished?quoId=${routerParam.quoId}&quoState=${
                    routerParam.quoState
                  }&batchNo=${payload.batchId}`
                )
              );
            }
          }
        } else {
          yield put({
            type: 'updateBatchTask',
            payload,
          });
        }
      }
    },

    // 上传文件  没有添加产品的批量
    *uploadFileHasProduct({ payload }, { call }) {
      yield call(service.socketChannel, {
        type: 'sub',
        data: { to: payload.batchId, type: 'task' },
      });
    },

    // 提交时获取批次号并获取进度的接口
    submitWithProgress:[
      function*(
      {
        payload: { routerParam },
      },
      { call, put, select }
    ) {
      const { batchId } = yield select(state => state.quoupdate);
      yield put({
        type: 'updateModelData',
        payload: {
          batchId,
          progressPercent: 0,
          showProgress: true,
          isSubmitResult: true,
          routerParam,
        },
      });
      yield call(service.socketChannel, {
        type: 'sub',
        data: { to: batchId, type: 'task' },
      });
    },
      { type:'throttle',ms:10000 }
    ]
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置查询时保存的值
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取客户名称
    getCustList(state, { payload }) {
      return {
        ...state,
        customerNameList: payload.data,
      };
    },
    // 当前的签约方
    getSuppList(state, { payload }) {
      return {
        ...state,
        suppReplaceCorpId: payload.data[0].suppId,
      };
    },

    // 获取全部签约方
    getByUserList(state, { payload }) {
      return {
        ...state,
        supplyList: payload.data,
      };
    },

    // 根据选择的供应商合同：请求客户名称
    getSuppsList(state, { payload }) {
      return {
        ...state,
        custId: payload.data[0].custId,
        customerNameList: payload.data,
      };
    },

    getCustIdList(state, { payload }) {
      return {
        ...state,
        contList: payload.data,
      };
    },

    getInfosList(state, { payload }) {
      return {
        ...state,
        contList: payload.data,
      };
    },

    getSuppIdsData(state, { payload }) {
      return {
        ...state,
        supplyContList: payload.data,
      };
    },

    getProduct(state, { payload }) {
      return {
        ...state,
        productData: payload.data,
      };
    },

    getUpdateDetailData(state, { payload }) {
      // 把每个包下的所有的产品下的地区合成一个地区（因为有多个地区）
      const newData = payload.data;
      return {
        ...state,
        updateDetailData: payload.data,
        originalData: payload.data,
        subUpdateDetailData: newData,
        taxes: payload.data && payload.data.taxFlag && payload.data.taxFlag.toString(), // 是否含税
        method: payload.data && payload.data.quoType && payload.data.quoType.toString(), // 报价方式
      };
    },

    clearInitialValue(state) {
      const temp = state;
      temp.updateDetailData.custId = undefined;
      temp.updateDetailData.custContId = undefined;
      temp.updateDetailData.serType = undefined;
      return {
        ...state,
      };
    },

    // 选择客户名称
    changeSerType(state, { payload }) {
      const temp = state;
      temp.updateDetailData.serType = payload.serType;
      return {
        ...state,
      };
    },

    clearUpdateValue(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 选择供应商合同的时候清空客户名称
    clearCustId(state) {
      const temp = state;
      temp.updateDetailData.custId = undefined;
      return {
        ...state,
      };
    },

    // 第二步往下一步跳的时候
    updateQuoData(state, { payload }) {
      return {
        ...state,
        getBatchId: payload.data.cacheKey,
        changQuoUpdateMessage: payload.data,
      };
    },

    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp === 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          tempType: payload.tempType,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
      }
      return {
        ...state,
        showProgress,
        progressPercent: payload.successProp,
        resultInfo,
        currentStep,
      };
    },

    // 更新提交批量任务数据
    updateSubmitBatchTask(state, { payload }) {
      let { showProgress, isSubmitResult } = state;
      showProgress = true;
      if (payload.successProp === 100) {
        showProgress = false;
        isSubmitResult = false;
      }
      return {
        ...state,
        isSubmitResult,
        showProgress,
        progressPercent: payload.successProp,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'task':
            dispatch({
              type: 'matchBatchId',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
